<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

/**
 * 推送管理
 */
class PushMessage extends Model
{
    protected $table = 'push_message';

    const TYPE_APP = 1;
    const TYPE_PUSH = 2;
    const TYPE_SYS = 3;
    const TYPE = [
        self::TYPE_APP => '官方推送消息',
        self::TYPE_PUSH => 'PUSH',
        self::TYPE_SYS => '系统消息（纯文字）',
    ];

    const MSG_TYPE_PIC = 'PIC';
    const MSG_TYPE_PIC_TEXT = 'PIC_TEXT';
    const MSG_TYPE_TEXT = 'TEXT';
    const MSG_TYPE_TEXT_LINK = 'TEXT_LINK';
    const MSG_TYPE = [
        self::MSG_TYPE_PIC => '纯图带跳转消息',
        self::MSG_TYPE_PIC_TEXT => '图文带跳转消息',
        self::MSG_TYPE_TEXT => '纯文字消息（有标题）',
        self::MSG_TYPE_TEXT_LINK => '纯文字带跳转消息（有标题）',
    ];

    const JUMP_TYPE_H5 = 'h5';
    const JUMP_TYPE_MAIN = 'user';
    const JUMP_TYPE_MOMENT = 'moment';
    const JUMP_TYPE_PROFILE = 'profile';
    const JUMP_TYPE_SOCIAL_PROFILE = 'social_profile';
    const JUMP_TYPE = [
        self::JUMP_TYPE_H5 => 'H5',
        self::JUMP_TYPE_MAIN => '个人主页',
        self::JUMP_TYPE_MOMENT => '动态',
        self::JUMP_TYPE_PROFILE => '个人资料修改',
        self::JUMP_TYPE_SOCIAL_PROFILE => '社交资料修改'
    ];

    /**
     * 查询相应的
     */
    static function selectUserIds(
        $gender = -1,
        $role = UserProfile::ROLE_USER,
        $recharge = false,
        $profileUserIds = []
    ) {
        $where = [];
        if ($gender > -1) $where[] = ['gender', $gender];
        if ($role > -1) $where[] = ['role', $role];
        $query = UserProfile::where($where);
        if ($recharge == 1) {
            $query = $query->join('pay_order', function ($join) {
                $join->on('user_profile.user_id', 'pay_order.user_id');
            })->where('pay_order.status', PayOrder::STATUS_OK);
        }

        if (!empty($profileUserIds)) {
            $query = $query->whereIn('user_profile_id', $profileUserIds);
        }
        $data = $query->select([\DB::raw('DISTINCT(t_user_profile.`user_id`)')])->get()->toArray();
        return array_column($data, 'user_id');
    }

    /**
     * 构造消息类型
     */
    static function buildMsgContent($model)
    {
        return [
            'title' => $model->push_title,
            'text' => $model->push_content,
            'pic' => '',
            'jump_info' => [
                'jump_type' => $model->jump_type,
                'jump_link' => $model->jump_link,
            ]
        ];
    }
}
